package wechat

import (
	"errors"
	"fitness/config"
	"github.com/medivhzhan/weapp/v3"
	"github.com/medivhzhan/weapp/v3/auth"
	"go.uber.org/zap"
)

// MiniApp 微信小程序服务
type MiniApp struct {
	client *weapp.Client
	auth   *auth.Auth
	logger *zap.Logger
	config *config.WeAppConfig
}

// NewMiniApp 创建微信小程序服务实例
func NewMiniApp(config config.WeAppConfig, logger *zap.Logger) *MiniApp {
	client := weapp.NewClient(
		config.AppID,
		config.AppSecret,
	)
	miniAppAuth := client.NewAuth()
	return &MiniApp{
		client: client,
		auth:   miniAppAuth,
		logger: logger,
		config: &config,
	}
}

// Code2Session 小程序登录凭证校验
func (m *MiniApp) Code2Session(code string) (*auth.Code2SessionResponse, error) {
	authResp, err := m.auth.Code2Session(&auth.Code2SessionRequest{
		Appid:     m.config.AppID,
		Secret:    m.config.AppSecret,
		JsCode:    code,
		GrantType: "authorization_code",
	})
	if err != nil {
		m.logger.Error("微信登录凭证校验失败", zap.Error(err), zap.String("code", code))
		return nil, err
	}

	if authResp.ErrCode != 0 {
		m.logger.Error("微信API返回错误", zap.Int("err_code", authResp.ErrCode), zap.String("err_msg", authResp.ErrMSG))
		return nil, errors.New(authResp.ErrMSG)
	}

	return authResp, nil
}

// GetUserInfo 获取用户信息
func (m *MiniApp) GetUserInfo(sessionKey, rawData, encryptedData, signature, iv string) (*weapp.UserInfo, error) {
	userInfo, err := m.client.DecryptUserInfo(sessionKey, rawData, encryptedData, signature, iv)
	if err != nil {
		m.logger.Error("获取微信用户信息失败", zap.Error(err))
		return nil, err
	}
	return userInfo, nil
}
